import { type Directive } from "vue";
// 自动聚焦指令
export const autoFocus: Directive<HTMLElement, string> = {
  mounted: function (el, id) {
    // 没传入id时,默认focus当前元素
    if (!id.value) {
      el.focus();
      return;
    }

    // 父元素就是传入id时,直接focus
    if (el.id === id.value) {
      el.focus();
      return;
    }

    const findElementFocus = (element: HTMLElement) => {
      const children = element.children;
      for (let i = 0; i < children.length; i++) {
        const childrenElement = children[i] as HTMLElement;
        // 子元素id匹配时focus
        if (childrenElement.id === id.value) {
          childrenElement.focus();
          return;
        }
        // 不匹配时递归寻找
        else findElementFocus(childrenElement);
      }
    };

    findElementFocus(el);
  },
};